<template>
    <div id="leftdown" style="width: 600px; height: 400px;"></div>
</template>

<script setup>
  import { onMounted, defineProps, watch, nextTick } from 'vue';
  import * as echarts from 'echarts';
  // 定义 props，接收父组件传递的数据
  const props = defineProps({
    childData2: Array
  });
  let myChart = null; // 存储 ECharts 实例
// 绘制左侧面
  const initECharts = () => {
    const echartsContainer = document.getElementById("leftdown");
    if (myChart) {
      // 如果已经存在 ECharts 实例，则先销毁它
      myChart.dispose();
    }
    // 初始化 ECharts 实例
    myChart = echarts.init(echartsContainer);
    // 检查childData1是否已定义
    if (!props.childData2 || props.childData2.length === 0) {
      console.warn('childData1 is not ready yet.');
      return; // 如果数据未准备好，直接返回不执行后续逻辑
    }
    const car = [];
    const totalSales = [];
    props.childData2.forEach(item => {
      car.push(item.car);
      totalSales.push(item.total_sales);
    });
 
    const option = {
    backgroundColor: '',
    tooltip : {
      trigger: 'axis',
      axisPointer : {            // 坐标轴指示器，坐标轴触发有效
          type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
  },
    xAxis: [{
        type: 'category',
        data: car,
        axisLine: {
            show: true,
            lineStyle: {
                color: "#063374",
                width: 1,
                type: "solid"
            }
        },
        axisTick: {
            show: false
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#00c7ff",
            }
        },
    }],
    yAxis: [{
        name:'销售量',
        splitLine: {show: false},
        axisLine: {
            lineStyle: {
                color: '#ccc',
            }
        },
        axisLabel:{
            formatter:'{value} Ha',
        }
    },
        ],
        dataZoom: [{
        type: 'slider',
        show: true,
        xAxisIndex: [0, 1, 2, 3],
        start: 50,
        end: 100
      }, {
        type: 'inside',
        xAxisIndex: [0, 1, 2, 3]
      }],
    series: [{
        type: 'bar',
        data: totalSales,
        //barWidth: 50, //柱子宽度
        //barGap: 1, //柱子之间间距
        itemStyle: {
            normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: '#00fcae'
                }, {
                    offset: 1,
                    color: '#006388'
                }]),
                opacity: 1,
            }
        }
    }]
};

    myChart.setOption(option);
  };
  
  // 修改onMounted钩子
  onMounted(async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  });
  
  // 修改watcher回调，添加async并使用nextTick
  watch(() => props.childData2, async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  }, { immediate: true });
  
  </script>





